package com.web.controller;

import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.web.pojo.Contract;
import com.web.pojo.User;
import com.web.service.ContractService;
import com.web.service.UserService;

@Controller
public class ContractController {

	@Autowired
	ContractService contractService;
	@Autowired
	UserService UserService;
	//日志打印
	private Logger logger = LoggerFactory.getLogger(ContractController.class);

	@RequestMapping("listContract")
	// 根据用户名称查询合同,同时判断是否为组长、区长、管理员,跳转不同的页面
	public String listContract(Model model, HttpServletRequest request) {
		//从请求获取Session
		User user = (User) request.getSession().getAttribute("users");;
		//Session为空返回登入
		if (user != null) {
			if ("管理员".equals(user.getRoleName())) {
				List<Contract> listcontract = contractService.listContract();
				model.addAttribute("listcontract", listcontract);
				logger.info("合同查询|查询成功|"+user.getUserName());
				return "contractManage-admin.jsp";
			}
			if ("销售经理".equals(user.getRoleName())) {
				List<Contract> listcontract = contractService.ContractByUserName(user.getUserName());
				model.addAttribute("listcontract", listcontract);
				logger.info("合同查询|查询成功| "+user.getUserName());
				return "contractManage-user.jsp";
			}
			/**
			 * 此处逻辑为先获取组长自己的合同，再通过所在的小组，找到组员，查每个组员（除自己）的合同，加到本身的合同集合里，输出
			 */
			if ("销售组长".equals(user.getRoleName())) {
				List<Contract> listcontract = contractService.ContractByUserName(user.getUserName());
				List<User> listuser = UserService.UserGetBygGoupName(user.getGroupName());
				for (User u : listuser) {
					if (!u.getUserName().equals(user.getUserName())) {
						listcontract.addAll(contractService.ContractByUserName(u.getUserName()));
					}
				}
				model.addAttribute("listcontract", listcontract);
				logger.info("合同查询|查询成功|"+user.getUserName());
				return "contractManage-user.jsp";
			}
			if ("销售区长".equals(user.getRoleName())) {
				List<Contract> listcontract = contractService.ContractByAreaName(user.getAreaName());
				model.addAttribute("listcontract", listcontract);
				logger.info("合同查询|查询成功|"+user.getUserName());
				return "contractManage-user.jsp";
			}
		}
		return "login.jsp";
	}
	
	@RequestMapping("deletecontract")
	//删除合同根据合同id
	public String deletecontract(String contractID) {
		boolean ret = contractService.deleteByContractID(contractID);
		System.out.println(ret+contractID);
		return "listContract";
	}
}
